package com.qian.ddj.web.controller;

import com.qian.api.ddj.model.CheckCode;
import com.qian.api.ddj.model.Code;
import com.qian.api.ddj.service.ICheckCodeService;
import com.qian.api.ddj.util.VerifyCodeUtils;
import com.yaowk.api.common.BaseException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/system/checkCode")
public class CheckCodeController {
    @Autowired
    private ICheckCodeService checkCodeService;

    @RequestMapping
    @ApiOperation("生成验证码")
    public void generate(HttpServletRequest request, HttpServletResponse response){
        CheckCode checkCode = new CheckCode();
        response.setContentType("image/jpeg");
        checkCode.setSessionId(request.getSession().getId());
        checkCode = checkCodeService.findOne(checkCode);
        if (!ObjectUtils.isEmpty(checkCode)){
            checkCodeService.deleteById(checkCode.getId());
            CheckCode checkCode1 = new CheckCode();
            String code = VerifyCodeUtils.generateVerifyCode(4);
            checkCode1.setCode(code);
            checkCode1.setSessionId(request.getSession().getId());
            checkCodeService.save(checkCode1);
            int w = 200, h = 80;
            try {
                VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), code);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(code);
        }else{
            String code = VerifyCodeUtils.generateVerifyCode(4);
            CheckCode checkCode1 = new CheckCode();
            checkCode1.setCode(code);
            System.out.println(code);
            checkCode1.setSessionId(request.getSession().getId());
            checkCodeService.save(checkCode1);
            int w = 200, h = 80;
            try {
                VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), code);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/verify")
    @ResponseBody
    @ApiOperation("验证验证码")
    public String verify(HttpServletRequest request, String code){
        CheckCode checkCode = new CheckCode();
        checkCode.setSessionId(request.getSession().getId());
        checkCode.setCode(code.toUpperCase());
        if (!checkCodeService.checkCode(checkCode)){
            return "error";
        }
        return "success";
    }
}
